package org.kl.wx.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton;
import me.chanjar.weixin.mp.api.WxMpService;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.ServiceException;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.kl.wx.entity.App;
import org.kl.wx.entity.WxLocolMenu;
import org.kl.wx.repository.WxMenuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Collections3;

@Component
@Transactional
public class WxMenuService {
	private WxMenuDao menuDao;
	@Autowired
	private AppService appService;

	public WxLocolMenu getMenu(String id) {
		return menuDao.find(WxLocolMenu.class, id);
	}

	public void saveMenu(WxLocolMenu entity) {
		menuDao.save(entity);
	}

	public void deleteMenu(String id) {
		menuDao.delete(id);
	}

	public List<WxLocolMenu> getAllMenu() {
		return menuDao.findAll();
	}

	public void saveMenu2(WxLocolMenu entity) {
		if (entity.getApp() == null) {
			throw new ServiceException("所属公众号不能为空！");
		}
		if (StringUtils.isBlank(entity.getId())) {// 如果是新增菜单
			if (StringUtils.isBlank(entity.getMenu().getId())) {// 新增根节点
				String appId = entity.getApp().getId();
				List<WxLocolMenu> menuList = menuDao.findByAppIdAndMenuId(appId, null);
				if (menuList.size() >= 3) {
					throw new ServiceException("同一公众号下一级菜单最多只能只有三个！");
				}

			} else {// 不是根节点
				WxLocolMenu menu = menuDao.findOne(entity.getMenu().getId());
				if (menu != null) {
					if (menu.getMenu() != null) {
						throw new ServiceException("同一公众号最多只能有两级菜单！");
					}
					if (!StringUtils.equals(menu.getApp().getId(), entity.getApp().getId())) {
						throw new ServiceException("菜单" + entity.getMenuName() + "与上级菜单" + menu.getMenuName() + "所属公众号不同！");
					}
				}
				List<WxLocolMenu> menus = menuDao.findByMenuId(entity.getMenu().getId());
				if (menus.size() >= 5) {
					throw new ServiceException("同一公众号同一一级菜单下，二级菜单最多只能有5个！");
				}

			}
		}
		menuDao.save(entity);

	}

	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				menuDao.delete(id);
				i++;
			}
		}
		return "成功删除" + i + "条记录";
	}

	// 同步微信菜单
	public void getMenu(WxMpService wxMpService, WxMenu wxMenu, String appId) {

		try {
			App app = appService.getAppByOriginAppId(appId);
			if (app != null) {
				List<WxLocolMenu> menuList = menuDao.findByAppId(app.getId());
				for (WxLocolMenu menu : menuList) {
					menuDao.delete(menu);
				}
			}
			if (wxMenu != null) {
				for (int i = 0; i < wxMenu.getButtons().size(); i++) {
					WxLocolMenu menu1 = new WxLocolMenu();
					menu1.setMenuName(wxMenu.getButtons().get(i).getName());
					menu1.setMenuKey(wxMenu.getButtons().get(i).getKey());
					menu1.setMenuType(wxMenu.getButtons().get(i).getType());
					menu1.setMenuUrl(wxMenu.getButtons().get(i).getUrl());
					menu1.setApp(app);
					menuDao.save(menu1);
					for (int j = 0; j < wxMenu.getButtons().get(i).getSubButtons().size(); j++) {
						WxLocolMenu menu2 = new WxLocolMenu();
						menu2.setApp(app);
						menu2.setMenu(menu1);
						menu2.setMenuKey(wxMenu.getButtons().get(i).getSubButtons().get(j).getKey());
						menu2.setMenuName(wxMenu.getButtons().get(i).getSubButtons().get(j).getName());
						menu2.setMenuType(wxMenu.getButtons().get(i).getSubButtons().get(j).getType());
						menu2.setMenuUrl(wxMenu.getButtons().get(i).getSubButtons().get(j).getUrl());
						menuDao.save(menu2);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 更新微信服务器菜单
	public void updateMenu(WxMpService wxMpService, String appId) {
		try {
			if (StringUtils.isBlank(appId)) {
				throw new ServiceException("所属公众号不能为空！");
			}
			List<WxLocolMenu> menus = menuDao.findByAppIdAndMenuId(appId, null);
			if (Collections3.isNotEmpty(menus)) {
				WxMenu wxMenus = new WxMenu();
				List<WxMenuButton> wxMenuButtonList1 = new ArrayList<WxMenuButton >();
				for (WxLocolMenu menu : menus) {
					WxMenuButton button = new WxMenuButton();
					button.setKey(menu.getMenuKey());
					button.setName(menu.getMenuName());
					button.setType(menu.getMenuType());
					button.setUrl(menu.getMenuUrl());

					List<WxLocolMenu> menuList = menuDao.findByMenuId(menu.getId());
					if (Collections3.isNotEmpty(menuList)) {
						List<WxMenuButton> wxMenuButtonList2 = new ArrayList<WxMenuButton >();
						for (WxLocolMenu menu2 : menuList) {
							WxMenuButton button2 = new WxMenuButton();
							button2.setKey(menu2.getMenuKey());
							button2.setName(menu2.getMenuName());
							button2.setType(menu2.getMenuType());
							button2.setUrl(menu2.getMenuUrl());
							wxMenuButtonList2.add(button2);
						}
						button.setSubButtons(wxMenuButtonList2);
					}
					wxMenuButtonList1.add(button);
				}
				wxMenus.setButtons(wxMenuButtonList1);

				wxMpService.menuDelete();
				wxMpService.menuCreate(wxMenus);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 生成treeGrid
	 * 
	 * @return
	 */
	public EasyuiGrid treeGrid() {
		List<WxLocolMenu> result = menuDao.findAll();
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(result);
		grid.setTotal(Collections3.isEmpty(result) ? 0 : result.size());
		return grid;
	}

	/**
	 * 按条件查询
	 */
	public List<WxLocolMenu> getMenu(Map<String, Object> searchParams) {
		Specification<WxLocolMenu> spec = buildSpecification(searchParams);
		return menuDao.findAll(spec);
	}

	/**
	 * 按条件分页查询
	 */
	public Page<WxLocolMenu> getMenu(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType, String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<WxLocolMenu> spec = buildSpecification(searchParams);

		return menuDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<WxLocolMenu> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<WxLocolMenu> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), WxLocolMenu.class);
		return spec;
	}

	@Autowired
	public void setMenuDao(WxMenuDao menuDao) {
		this.menuDao = menuDao;
	}

}
